#!/bin/bash
APPIMAGETOOL="./.cache/build-tools/appimagetool"
RELEASE_CHANNEL=${RELEASE_CHANNEL:-"stable"}

mkdir -p ./.cache/build-tools
wget https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage -O "${APPIMAGETOOL}" || { echo "Failed to download appimagetool."; exit 1; }
chmod +x "${APPIMAGETOOL}"

if [ "${RELEASE_CHANNEL}" != "stable" ]; then
    APP_DIR=./src-tauri/target/release/bundle/appimage/Jan-${RELEASE_CHANNEL}.AppDir
    LIB_DIR=$APP_DIR/usr/lib/Jan-${RELEASE_CHANNEL}/binaries
else
    APP_DIR=./src-tauri/target/release/bundle/appimage/Jan.AppDir
    LIB_DIR=$APP_DIR/usr/lib/Jan/binaries
fi

# bundle additional resources in the AppDir without pulling in their dependencies
cp ./src-tauri/resources/bin/bun $APP_DIR/usr/bin/bun
mkdir -p $LIB_DIR/engines

# remove appimage generated by tauri build
APP_IMAGE=./src-tauri/target/release/bundle/appimage/$(ls ./src-tauri/target/release/bundle/appimage/ | grep AppImage | head -1)
echo $APP_IMAGE
rm -f $APP_IMAGE

# repackage appimage with additional resources
"${APPIMAGETOOL}" $APP_DIR $APP_IMAGE